package com.yycx.module.bus.provider.handler.haiying.tasktodo.saleman;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yycx.bpm.provider.common.handler.ProcessStartHandler;
import com.yycx.bpm.provider.model.ProcessInstanceRequest;
import com.yycx.common.utils.ApiAssert;
import com.yycx.module.bus.client.entity.BusSaleman;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.provider.service.BusSalemanService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 启动业务员审核流程
 *
 * @author zyf
 */
@Component
@DSTransactional
@Slf4j
public class SaleManStartProcessHandler implements ProcessStartHandler {

    @Autowired
    private BusSalemanService saleManService;

    /**
     * 初始化流程参数
     *
     * @param processInstanceRequest
     * @return
     */
    @Override
    public String init(ProcessInstanceRequest processInstanceRequest) {
        processInstanceRequest.setProcessKey("process_saleman_flp");
        processInstanceRequest.setTenantId("flp");
        return processInstanceRequest.getBusinessKey();
    }

    /**
     * 设置全局流程变量
     *
     * @param processInstanceRequest
     * @param definition
     * @return
     */
    @Override
    public Map<String, Object> initVariables(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition) {
        Map<String, Object> map = new HashMap<>(5);
        String businessKey = processInstanceRequest.getBusinessKey();
        BusSaleman saleman = saleManService.getById(businessKey);
        if (!saleman.getSalemanState().equals(-2)) {
            ApiAssert.failure("请勿重复提交");
        }
        String saleManName = saleman.getSaleManName();
        map.put("saleManName", saleManName);
        return map;
    }

    /**
     * 启动完成业务处理
     *
     * @param processInstanceRequest 请求参数
     * @param definition             流程定义
     * @param processInstance        流程实例
     * @param tasks                  任务列表
     * @param variables              流程变量
     */
    @Override
    public Boolean afterComplete(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition, ProcessInstance processInstance, List<Task> tasks, Map<String, Object> variables) {
        String businessKey = processInstanceRequest.getBusinessKey();
        saleManService.updateSaleManState(Long.parseLong(businessKey),processInstance.getProcessInstanceId(), -1);
        return true;

    }
}
